﻿namespace System
{
    /// <summary>
    /// 
    /// </summary>
    public static class LazyExtensions
    {
        /// <summary>
        /// 当<paramref name="lazy"/>的值已创建且值继承<see cref="IDisposable"/>则调用<see cref="IDisposable.Dispose"/>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="lazy"></param>
        public static void Disposable<T>(this Lazy<T> lazy)
        {
            if (lazy!=null && lazy.IsValueCreated && lazy.Value is IDisposable dis)
                dis.Dispose();
        }
    }


#if NET35

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Lazy<T>
    {
        private T _value;

        private readonly Func<T> _valueFactory;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="valueFactory"></param>
        public Lazy(Func<T> valueFactory)
        {
            _valueFactory = valueFactory;
            IsValueCreated = false;
        }

        /// <summary>
        /// 
        /// </summary>
        public bool IsValueCreated { get; private set; }


        /// <summary>
        /// 
        /// </summary>
        public T Value
        {
            get
            {
                if (!IsValueCreated)
                {
                    lock (this)
                        if (!IsValueCreated)
                        {
                            _value = _valueFactory();
                            IsValueCreated = true;
                        }
                }
                return _value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return Value?.ToString();
        }

    }
#endif

}
